package com.ruin.tech.ahri.utils;

import com.ruin.tech.ahri.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * @program ahri
 * @description: 工具类
 * @author: ruin
 * @create: 2019/11/28 11:14
 */
@Slf4j
public class Utils {
    private static final String innerSalt = "itruin";

    public static int radomInt(){
        Random random = new Random();
        int x = random.nextInt(899999);
        x = x + 100000;
        return x;
    }

    public static void wirteFile(MultipartFile file, File pFile) throws IOException {
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(pFile);
            fos.write(file.getBytes());
        }catch(Exception e){
            throw e;
        }finally {
            fos.close();
        }
    }

    public static String getBasePath(){
        HttpServletRequest request = Utils.getHttpServletRequest();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
        return basePath;
    }

    public static HttpServletRequest getHttpServletRequest(){
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder
                .getRequestAttributes())
                .getRequest();
        return request;
    }

    public static String digestString(String password, String salt) {
        if(salt == null){
            salt = innerSalt;
        }
        String digestStr = DigestUtils.sha256Hex(DigestUtils.sha256Hex(password)+salt);
        return digestStr;
    }
}
